<template>
  <div class="content-area">
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <div>
              <h2>用户缴费管理</h2>
            </div>

            <el-select
                v-model="value"
                placeholder="选择某一小区"
                size="large"
                style="width: 240px; margin-left: 10px;"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
              />
            </el-select>

            <el-button
                type="primary"
                size="large"
                style="margin-left: 10px;"
                @click="clearSelection"
            >
              清空选择
            </el-button>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
          <div class="table-header-container">
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按缴费状态查询" value="paymentStatus"></el-option>
                <el-option label="按业主id查询" value="ownerId"></el-option>
                <el-option label="按房屋id和所属月份查询" value="houseIdFeeMonth"></el-option>
              </el-select>
              <el-input v-model="searchQuery"
                        :placeholder="
                  searchOption === 'paymentStatus'? '0--未缴费，1--已缴费' :
                  searchOption === 'houseIdFeeMonth'? '房屋id-所属月份' :
                  '请输入查询关键词'
                "
                        class="search-input"></el-input>
              <el-button type="primary" @click="searchChargeDetail" class="search-button">查询</el-button>
            </div>
            <el-button type="primary" @click="handleCommunity">增加记录</el-button>
          </div>
          <table v-if="chargeDetailForm && chargeDetailForm.data && chargeDetailForm.data.records"
                 style="text-align: center; width: 100%; border-collapse: collapse;">
            <thead>
            <tr style="border: 1px solid #eee;">
              <th style="width: 100px;  border: 1px solid #eee;">缴费详情id</th>
              <th style="width: 100px;  border: 1px solid #eee;">业主id</th>
              <th style="width: 100px;  border: 1px solid #eee;">房屋id</th>
              <th style="width: 80px;  border: 1px solid #eee;">收费项目id</th>
              <th style="width: 80px;  border: 1px solid #eee;">负责收费的物业id</th>
              <th style="width: 100px;  border: 1px solid #eee;">用量</th>
              <th style="width: 200px;  border: 1px solid #eee;">总金额</th>
              <th style="width: 100px;  border: 1px solid #eee;">费用所属月份</th>
              <th style="width: 80px;  border: 1px solid #eee;">缴费状态</th>
              <th style="width: 200px;  border: 1px solid #eee;">订单产生时间</th>
              <th style="width: 100px;  border: 1px solid #eee;">缴费时间</th>
              <th style="width: 200px;  border: 1px solid #eee;">订单号</th>
              <th style="width: 50px;  border: 1px solid #eee;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in chargeDetailForm.data.records" :key="index" style="border: 1px solid #eee;">
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.id" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.ownerId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.houseId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.chargeId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.propertyStaffId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.dosage" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.amount" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.feeMonth" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.paymentStatus" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.createDate" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.paymentDate" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.traceNo" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <div class="button-group">
                  <el-button type="success" @click="toggleStatus(item)">更新缴费状态</el-button>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
          <div v-else-if="errorMessage">{{ errorMessage }}</div>
          </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="chargeDetailForm && chargeDetailForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[8, 10, 12]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="chargeDetailForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>
    <el-dialog v-model="addDialogFormVisible" title="增加缴费项目" width="500">
      <el-form :model="addForm">
        <el-form-item label="业主id" :label-width="formLabelWidth">
          <el-input v-model="addForm.ownerId" placeholder="请输入业主id" />
        </el-form-item>
        <el-form-item label="房屋id" :label-width="formLabelWidth">
          <el-input v-model="addForm.houseId" placeholder="请输入房屋id" />
        </el-form-item>
        <el-form-item label="收费项目id" :label-width="formLabelWidth">
          <el-input v-model="addForm.chargeId" placeholder="请输入收费项目id" />
        </el-form-item>
        <el-form-item label="负责的物业id" :label-width="formLabelWidth">
          <el-input v-model="addForm.propertyStaffId" placeholder="请输入负责收费的物业id" />
        </el-form-item>
        <el-form-item label="用量" :label-width="formLabelWidth">
          <el-input v-model="addForm.dosage" placeholder="请输入用量" />
        </el-form-item>
        <el-form-item label="总金额" :label-width="formLabelWidth">
          <el-input v-model="addForm.amount" placeholder="请输入总金额" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>



  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  data() {
    return {
      errorMessage: '',
      currentPage: 1,
      pageSize: 12,
      addDialogFormVisible: false,
      addForm: {
        ownerId: "",
        houseId: "",
        chargeId: "",
        propertyStaffId: "",
        dosage: "",
        amount: "",
        feeMonth: "",
        paymentStatus: "",
        createDate: "",
        paymentDate: "",
        traceNo: "",
        communityId: this.communityId
      },
      chargeDetailForm: {
        id: "",
        ownerId: "",
        houseId: "",
        chargeId: "",
        propertyStaffId: "",
        dosage: "",
        amount: "",
        feeMonth: "",
        paymentStatus: "",
        createDate: "",
        paymentDate: "",
        traceNo: "",
        communityId: this.communityId
      },
      communityId: "",
      searchOption:"",
      isEdit: false,
      saveEditId: null,
      originalInfo: null,
      searchQuery: '',
      deleteId: null,
      deleteDialogFormVisible: false,
      formLabelWidth: '120px',
      value: null,
      communityList: null
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchData();
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchData();
    },
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        this.communityList = response.data.data;
        console.log('this.community',this.communityList)
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    handleCommunity(){
      if(this.communityId) {
        this.addDialogFormVisible = true;
      }else{
        ElMessage.info('请先选择小区')
      }
    },
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          communityId: this.communityId
        };
        if (this.searchOption =='paymentStatus') {
          params.paymentStatus = this.searchQuery;
        }else if(this.searchOption == 'ownerId'){
          params.ownerId = this.searchQuery;
        }else if(this.searchOption == 'houseIdFeeMonth'){
          params.houseId = this.searchQuery.split('-')[0];
           params.feeMonth = this.searchQuery.split('-')[1];
        }
        const response = await axios.get('/api/charge-details/page', {
          headers: {
            Authorization: token
          },
          params: params
        });
        this.chargeDetailForm = response.data;
        this.originalInfo = {...this.chargeDetailForm} ;
        console.log(response.data);
      } catch (error) {
        ElMessage.error('获取收费详情列表数据统计失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async confirmAdd() {
      try {

          const token = localStorage.getItem('token');
          const response = await axios.post(`/api/charge-details/${this.communityId}`, null, {
            headers: {
              Authorization: token
            },
            params: {
              houseID: this.addForm.houseId,
              chargeID: this.addForm.chargeId,
              propertyStaffID: this.addForm.propertyStaffId,
              dosage: this.addForm.dosage,
              amount: this.addForm.amount
            }
          });
          console.log('charge', response);
          if (response.data.code === 200) {
            ElMessage.success('增加收费详情记录成功');
            this.addDialogFormVisible = false;
          } else {
            ElMessage.error('增加收费详情记录失败,请输入正确信息');
          }
          this.fetchData();

      }catch (error) {
        ElMessage.error('增加收费详情记录时出错：' + error.message);
      }
    },
    async searchChargeDetail() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'paymentStatus') {
          const response = await axios.get('/api/charge-details/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              paymentStatus: this.searchQuery
            }
          });
          console.log(response.data)
          if (response.data.code === 200) {
            // this.chargeDetailForm.data.records = response.data.data;
            this.chargeDetailForm = response.data;
            this.originalInfo = {...this.chargeDetailForm };
          } else {
            ElMessage.error('查询收费详情信息失败');
          }
        }else if (this.searchOption === 'ownerId') {
          const response = await axios.get('/api/charge-details/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              ownerId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.chargeDetailForm = response.data;
            this.originalInfo = {...this.chargeDetailForm };
          } else {
            ElMessage.error('查询收费详情信息失败');
          }
        }else if (this.searchOption === 'houseIdFeeMonth') {
          const response = await axios.get('/api/charge-details/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              houseId: this.searchQuery.split('-')[0], // 假设编号格式为 房屋ID-费用所属月份
              feeMonth: this.searchQuery.split('-')[1]
            }
          });
          if (response.data.code === 200) {
            this.chargeDetailForm = response.data;
            this.originalInfo = {...this.chargeDetailForm };
          } else {
            ElMessage.error('查询收费详情信息失败');
          }
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    },
    async toggleStatus(item) {
      const statusOrder = [0, 1];
      const currentIndex = statusOrder.indexOf(item.paymentStatus);
      const newStatus = statusOrder[(currentIndex + 1) % statusOrder.length];
      const token = localStorage.getItem('token');
      try {
        const response = await axios.put(`/api/charge-details/${item.id}/status`, null, {
          headers: {
            Authorization: token
          },
          params: {
            paymentStatus: newStatus
          }
        });
        if (response.status === 200) {
          item.paymentStatus = newStatus;
          ElMessage.success('处理状态更新成功');
        } else {
          ElMessage.error('处理状态更新失败');
        }
        this.fetchData();
      } catch (error) {
        ElMessage.error('处理状态更新失败，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchData();
    this.fetchCommunityList();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-input {
  flex: 1;
  width: 250px;
  margin-right: 10px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}


.disabled-style {
  cursor: default;
}

.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}
.search-input {
  flex: 1;
  width: 400px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}
</style>